package org.hxyjs.dao.impl;

import org.hxyjs.dao.TeamDao;
import org.hxyjs.entity.Team;
import org.hxyjs.mapper.TeamMapper;
import org.hxyjs.page.PageInfo;
import org.hxyjs.utils.GenNumTools;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Repository("teamDao")//一般实现类不会直接生成默认对象名 而是使用 接口的默认对象名
public class TeamDaoImpl implements TeamDao {
    @Resource //autowired 会装配能够直接扫描到的对象  resource spring容器运行的时候才找到需要的对象  注入
    private TeamMapper teamMapper;

    //查询全部
    public List<Team> getAllTeams() throws Exception {
        return teamMapper.selectByExample(null);
    }

    //按主键查询
    @Override
    public Team getTeamByTno(String tno) throws Exception {
        return teamMapper.selectByPrimaryKey(tno);
    }

    //分页查询
    @Override
    public List<Team> getTeamByPage(PageInfo pageInfo) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("currPage", pageInfo.getCurrPage());
        map.put("pageSize", pageInfo.getPageSize());
        int itemCount = (int) teamMapper.countByExample(null);
        pageInfo.setItemCount(itemCount);
        return teamMapper.getTeamByPage(map);
    }

    //删除
    @Override
    public Integer deleteTeamByTno(String tno) {
        return teamMapper.deleteByPrimaryKey(tno);
    }

    //修改
    @Override
    public Integer updateTeamByTno(Team team) {
        return teamMapper.updateByPrimaryKey(team);
    }


    //增加
    @Override
    public Integer addTeam(Team team) {
        team.setTno(initId());
        return teamMapper.insertSelective(team);
    }

    public String initId() {
        String maxTno = teamMapper.getMaxTno();
        maxTno = Optional.ofNullable(maxTno).orElse("0000");
        return GenNumTools.initId("t", 4, maxTno);
    }

}